<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2017/9/7
 * Time: 15:10
 */

namespace Admin\Logic;


use Common\Utils\Constants;
use Home\Logic\MatchLogLogic;
use Home\Logic\PayLogic;
use phpDocumentor\Reflection\DocBlock\Tags\Return_;
use Think\Exception;
use Think\Log;

class UserLogic
{
    private $tree = array();
    private $userList =array();
    /**
     * @param $user_id int 用户id
     * @param $username string 用户登录名
     * @param $password string 密码
     * @return int
     */
    public function setReferee($user_id,$username,$password){
        $model = M();
        $model->startTrans();
        $admin = D('Admin')->where(array('user_id'=>$user_id))->find();
        $count = D('Admin')->where(array('username'=>$username))->count();
        if(!$admin){
            if($count > 0){
                return 2;//登录名已经被使用
            }
        }
        try {
            $admin['user_id'] = $user_id;
            $admin['password'] = md5($password . C('MD5_KEY'));
            $admin['username'] = $username;
            $admin['is_use'] = 1;
            if ($count == 0) {//首次添加
                $admin_id = $model->table('t_admin')->add($admin);
                $admin_role['admin_id'] = $admin_id;
                $admin_role['role_id'] = 4;//裁判
                $model->table('t_admin_role')->add($admin_role);
            } else {
                $model->table('t_admin')->save($admin);
            }
            $model->table('t_user')->where(array('id' => $user_id))->setField('is_referee', 1);
            $model->commit();
            return 1;
        }catch (Exception $e){
            $model->rollback();
            Log::write('ajaxSetReferee---'.$e->getMessage());
            return 0;
        }
    }

    /**
     * 设置用户成为代理
     * @param $user_id int 用户id
     * @return int
     */
    public function setAgent($user_id){
        $user = D('User')->where(array('id'=>$user_id))->find();
        if($user['user_type'] == Constants::USER_TYPE_AGENT){
            return 2;
        }
        $model = M();
        $model->startTrans();
        try{
            $model->table('t_user')->where(array('id'=>$user_id))->setField('user_type',Constants::USER_TYPE_AGENT);
            $model->table('t_user')->where(array('id'=>$user_id))->setField('last_one',NULL);
            $list = $this->getDownUserInfoById($user_id);
            Log::write('setAgent count:'.count($list));
            foreach ($list as $key=>$value){
                if($value['user_type'] ==Constants::USER_TYPE_AGENT){
                    continue;
                }
                if(empty($value['last_one'])){
                    $model->table('t_user')->where(array('id'=>$value['id']))->setField('last_one',$user_id);
                }
            }
            $model->commit();
            return 1;
        }catch (Exception $e){
            Log::write("setAgent:---".$e->getMessage());
            $model->rollback();
            return 0;
        }
    }

    public function cancelAgent($user_id){
        $user = D('User')->where(array('id'=>$user_id))->find();
        if($user['user_type'] !=  Constants::USER_TYPE_AGENT){
            return 2;
        }
        $model = M();
        $model->startTrans();
        try{
            $model->table('t_user')->where(array('last_one'=> $user_id))->setField('last_one',NULL);
            $model->table('t_user')->where(array('id'=> $user_id))->setField('user_type',Constants::USER_TYPE_ORDINARY);
            $model->commit();
            return 1;
        }catch (Exception $e){
            Log::write("cancelAgent:---".$e->getMessage());
            $model->rollback();
            return 0;
        }
    }

    public function getDownUserInfoById($user_id){
        $this->tree[] = $user_id;
        $this->getUserListByParent(0);
        if(count($this->userList) == 0){
            return array();
        }
        $list =D('User')
            ->where(array('id'=>array('in',$this->userList)))
            ->field('id,last_one,user_type')
            ->select();
        return $list;
    }

    private function getUserListByParent($index){
//        var_dump($this->tree);
        if(!$this->tree)    return  ;  //数组为空时说明遍历结束return
        $user  =  M('User')->where(array('id'=>  $this->tree[$index]))->field('id')->find();
        //出队
        if($index != 0) {
            $this->userList[] = $this->tree[$index];
        }
        unset($this->tree[$index]);
        //找孩子
        $son = M('User')->where(array('recommend_id'=> $user['id']))->field('id')->select();
        if($son) {
            //将孩子加入tree数组不更新用户信息 入队
            $this->sonRebate($son);
        }
        $this->getUserListByParent($index+1);
//        var_dump($this->tree);

    }

    private function  sonRebate($son){
        foreach ($son as $sonk => $sonv) {
            $this->tree[] = $sonv['id'];
        }
    }

    /**
     * 增减用户钻石
     * @param $user_id int 用户id
     * @param $integral int 钻石
     * @return int 0失败 1成功 2用户不存在 3输入钻石数目不正确
     */
    public function setUserIntegral($user_id,$integral){
        $count = D('User')->where(array('id'=>$user_id))->count();
        if($count == 0){
            return 2;
        }
        if(!is_numeric($integral) || $integral==0){
            return 3;
        }
        $model = M();
        $model->startTrans();
        try{
            if($integral > 0){
                $remark = '系统赠送钻石';
                $model->table('t_user')->where(array('id'=>$user_id))->setInc('integral',$integral);
                $put_type = Constants::PUT_TYPE_IN;
                $money_type = Constants::MONEY_SOURCE_SYSTEM_GIVE;
            }else{
                $remark = '系统扣除钻石';
                $put_type = Constants::PUT_TYPE_OUT;
                $model->table('t_user')->where(array('id'=>$user_id))->setDec('integral',abs($integral));
                $money_type = Constants::MONEY_SOURCE_SYSTEM_DEDUCTION;
            }
            $currentMoney = $model->table('t_user')->where(array('id'=>$user_id))->getField('integral');
            $moneyLogic = new MoneyLogLogic();
            $moneyLogic->saveMoneyLog(abs($integral),
                $currentMoney,
                $money_type,
                $put_type,
                $remark,$user_id,Constants::MONEY_TYPE_INTEGRAL,$model);
            $model->commit();
            return 1;
        }catch (Exception $e){
            $model->rollback();
            Log::write('setUserIntegral:-----'.$e->getMessage());
            return 0;
        }

    }

    /**
     * 清空代理的可提现金额
     * @param $user_id int 用户id
     * @return int 0失败 1成功 2该用户不存在 3可提金额为0
     */
    public function clearUserIncome($user_id){
        $model = M();
        $model->startTrans();
        try{
            $count = $model->table('t_user')->where(array('id'=>$user_id))->count();
            if($count == 0){
                return 2;
            }
            $income = $model->table('t_user')->where(array('id'=>$user_id))->getField('income');
            if($income <= 0){
                return 3;
            }
            $model->table('t_user')->where(array('id'=>$user_id))->setInc('total_withdraw',$income);
            $model->table('t_user')->where(array('id'=>$user_id))->setField('income',0);
            $moneyLogic = new MoneyLogLogic();
            $moneyLogic->saveMoneyLog($income,
                0,
                Constants::MONEY_SOURCE_WITHDRAW,
                Constants::PUT_TYPE_OUT,
                '代理提现',$user_id,Constants::MONEY_TYPE_INCOME,$model);
            $model->commit();
            return 1;
        }catch (Exception $e){
            $model->rollback();
            Log::write('clearUserIncome:-----'.$e->getMessage());
            return 0;
        }
    }

    /**
     * 清空用户浏览量
     * @param $user_id int 用户id
     * @return int 0失败 1成功 2该用户不存在 3用户浏览量为0
     */
    public function clearPageviews($user_id){
        $model = M();
        $model->startTrans();
        try{
            $count = $model->table('t_user')->where(array('id'=>$user_id))->count();
            if($count == 0){
                return 2;
            }
//            $income = $model->table('t_user')->where(array('id'=>$user_id))->getField('pageviews');
//            if($income <= 0){
//                return 3;
//            }
            $model->table('t_user')->where(array('id'=>$user_id))->setField('show_pageviews',0);
            $model->table('t_user')->where(array('id'=>$user_id))->setField('count_pageviews',0);
            $model->commit();
            return 1;
        }catch (Exception $e){
            $model->rollback();
            Log::write('clearPageviews:-----'.$e->getMessage());
            return 0;
        }
    }

}